package cn.edu.buu.hospital.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MyBatisUtil {
    // 静态SqlSessionFactory，全局唯一
    private static SqlSessionFactory sqlSessionFactory;
    // 线程局部变量，保证多线程环境下SqlSession的线程安全
    private static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();

    // 静态初始化块，项目启动时加载MyBatis配置并创建SqlSessionFactory
    static {
        String config = "mybatis-config.xml"; // 对应MyBatis核心配置文件
        try (InputStream inputStream = Resources.getResourceAsStream(config)) {
            // 构建SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MyBatis工具类初始化失败：" + e.getMessage());
        }
    }

    // 获取当前线程的SqlSession（若不存在则创建并绑定到线程）
    public static SqlSession getSqlSession() {
        SqlSession sqlSession = THREAD_LOCAL.get();
        if (sqlSession == null) {
            // 手动控制事务（false表示关闭自动提交）
            sqlSession = sqlSessionFactory.openSession(false);
            THREAD_LOCAL.set(sqlSession);
        }
        return sqlSession;
    }

    // 提交事务
    public static void commit() {
        SqlSession sqlSession = THREAD_LOCAL.get();
        if (sqlSession != null) {
            sqlSession.commit();
        }
    }

    // 回滚事务
    public static void rollback() {
        SqlSession sqlSession = THREAD_LOCAL.get();
        if (sqlSession != null) {
            sqlSession.rollback();
        }
    }

    // 关闭SqlSession并移除线程绑定
    public static void closeSqlSession() {
        SqlSession sqlSession = THREAD_LOCAL.get();
        if (sqlSession != null) {
            sqlSession.close();
            THREAD_LOCAL.remove(); // 防止内存泄漏
        }
    }
}
